package com.jar.exercise.多线程.线程之间的通信;

public class SynchronizedProduceAndConsume {
    public static void main(String[] args) {
        Factory factory = new Factory();
        new Thread(factory::produce).start();
        new Thread(factory::consume).start();
    }
}

class Factory {
    private static int count;
    private boolean flag;

    public synchronized void produce() {
        try {
            while (true) {
                if (count > 100) {
                    break;
                }
                if (!flag) {
                    count++;
                    System.out.println("生产者生产了第：" + count + " 个产品");
                    flag = true;
                    this.notifyAll();
                } else {
                    this.wait();
                }

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void consume() {
        try {
            while (true) {
                if (count > 100) {
                    break;
                }
                if (flag) {
                    flag = false;
                    System.out.println("消费者消费了第：" + count + " 个产品");
                    this.notifyAll();
                } else {
                    this.wait();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

